var wxReady = false;
var env;

function loadJs(js, func) {
	var s = document.createElement('script');
	s.src = js;
	document.body.appendChild(s);
	if (func)
		s.onload = func;
}

if (/wxwork/.test(navigator.userAgent)) env = 'qywx';
else if (/micromessenger/.test(navigator.userAgent.toLowerCase())) env = 'wx';
else loadJs('/wechat/js/pswp.js');

top.wxReadyFunc = function () {
	top.wxReady = true;
};

function wxConfig() {
	var url = location.href.split('#')[0];
	if (env == 'qywx') url = encodeURIComponent(url);

	axios.get('/api/jsapi', { params: { url: url } }).then(function (res) {
		var o = res.data;
		if (env == 'qywx') o.beta = true;
		wx.config(Object.assign(o, {
			debug: false,
			jsApiList: ['chooseImage', 'uploadImage', 'previewImage',
				'startRecord', 'stopRecord', 'onVoiceRecordEnd',
				'onVoicePlayEnd', 'uploadVoice']
		}));

		wx.ready(top.wxReadyFunc);
		wx.error(function (res) {
			axios.post('/api/report', {
				href: location.href,
				msg: '微信config失败：' + res.errMsg,
			}).then(function (res) { });
		});
	});
}

function wxInit() {
	if (self == top) {
		top.wx = wx;
		return wxConfig();
	}
	if (top.wxReady) {
		wxReady = true;
		return;
	}
	top.wxReadyFunc = function () {
		wxReady = true;
	};

	var interval = setInterval(function () {
		if (wxReady)
			return clearInterval(interval);

		if (top.wxReady) {
			wxReady = true;
		}
	}, 500);
}


if (env == 'wx') loadJs('https://res.wx.qq.com/open/js/jweixin-1.6.0.js', wxInit);
else if (env == 'qywx') loadJs('https://res.wx.qq.com/open/js/jweixin-1.2.0.js', wxInit);

function wxChooseImg(count, field, func) {
	if (!wxReady)
		return uplaodImg(field, func);

	top.wx.chooseImage({
		count: count,
		sizeType: ['compressed'],
		success: function (res) {
			var a = res.localIds;

			function upload() {
				if (!a.length) return;
				top.wx.uploadImage({
					localId: a.shift(),
					success: function (res) {
						upload();
						axios.get('/api/img/' + getPerson().schoolId + '/' + field, {
							params: {
								serverId: res.serverId,
								skip: func.skip
							}
						}).then(function (res) {
							if (/\.json$/.test(res.data.data))
								return;

							func(res.data.data);
						});
					}
				});
			}

			upload();
		},
	});
}

function wxPreviewImg(pics, index) {
	pics = pics.map(function (it) {
		if (/^http/.test(it)) return it;
		return location.origin + it;
	});

	if (!wxReady)
		return previewImg(pics, index);

	top.wx.previewImage({
		current: pics[index],
		urls: pics
	});
}

function bindPreview() {
	var x = document.querySelectorAll('#vue-root div img');
	for (var i = 0; i < x.length; i++)
		(function () {
			var it = x[i];
			it.onclick = function () {
				wxPreviewImg([it.src], 0);
			};
		})();
}



